using ERP.RepositoryManage;
using ERP.RepositoryManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Text.Json;

namespace ERP.Web.Controllers
{
    /// <summary>
    /// 装箱管理控制器
    /// </summary>
    public class PackingController : Controller
    {
        private readonly IPackingService _packingService;

        public PackingController(IPackingService packingService)
        {
            _packingService = packingService;
        }

        /// <summary>
        /// 装箱管理首页
        /// </summary>
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取装箱管理树形列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetTreeList(GetPackingInputDto input = null)
        {
            try
            {
                input = input ?? new GetPackingInputDto();
                
                // 添加调试信息
                System.Diagnostics.Debug.WriteLine($"GetTreeList called with input: {JsonSerializer.Serialize(input)}");
                
                var result = await _packingService.GetTreeListAsync(input);
                
                System.Diagnostics.Debug.WriteLine($"GetTreeList result count: {result?.Count ?? 0}");
                
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"GetTreeList error: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"GetTreeList stack trace: {ex.StackTrace}");
                
                return Json(new { code = 1, msg = ex.Message, data = new object[0] });
            }
        }

        /// <summary>
        /// 获取装箱管理分页列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetList([FromBody] GetPackingInputDto input)
        {
            try
            {
                var result = await _packingService.GetListAsync(input);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 获取装箱管理详情
        /// </summary>
        [HttpGet]
        public async Task<JsonResult> GetDetail(int id)
        {
            try
            {
                var result = await _packingService.GetAsync(id);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 创建装箱管理
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Create([FromBody] CreatePackingDto input)
        {
            try
            {
                var result = await _packingService.CreateAsync(input);
                return Json(new { code = 0, msg = "创建成功", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 更新装箱管理
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Update([FromBody] UpdatePackingDto input)
        {
            try
            {
                var result = await _packingService.UpdateAsync(input.Id, input);
                return Json(new { code = 0, msg = "更新成功", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 删除装箱管理
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Delete(int id)
        {
            try
            {
                await _packingService.DeleteAsync(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 生成装箱单编号
        /// </summary>
        [HttpGet]
        public async Task<JsonResult> GeneratePackingCode()
        {
            try
            {
                var code = await _packingService.GeneratePackingCodeAsync();
                return Json(new { code = 0, msg = "success", data = code });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 添加子箱
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> AddSubPacking(int parentId, int subPackingId)
        {
            try
            {
                var result = await _packingService.AddSubPackingAsync(parentId, subPackingId);
                return Json(new { code = 0, msg = "添加子箱成功", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 获取可选择的装箱列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetParentPackingSelectList(string packingCode = "", string customerCode = "", string productCode = "", int excludeId = 0, int page = 1, int limit = 10)
        {
            try
            {
                var input = new GetPackingInputDto
                {
                    PackingCode = packingCode,
                    CustomerCode = customerCode,
                    SkipCount = (page - 1) * limit,
                    MaxResultCount = limit
                };
                
                var result = await _packingService.GetParentPackingSelectListAsync(input);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 获取装箱明细列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetPackingDetails(int packingId, int page = 1, int limit = 10)
        {
            try
            {
                var result = await _packingService.GetPackingDetailsAsync(packingId);
                return Json(new { code = 0, msg = "success", count = result.Count, data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 添加装箱明细
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> CreatePackingDetail([FromBody] System.Text.Json.JsonElement requestData)
        {
            try
            {
                // 手动解析请求数据，使用更安全的类型转换
                var input = new CreatePackingDetailDto
                {
                    PackingId = ParseInt(requestData, "packingId", 0),
                    WorkOrderCode = requestData.TryGetProperty("workOrderCode", out var workOrderCode) ? workOrderCode.GetString() ?? string.Empty : string.Empty,
                    MaterialCode = requestData.TryGetProperty("materialCode", out var materialCode) ? materialCode.GetString() ?? string.Empty : string.Empty,
                    MaterialName = requestData.TryGetProperty("materialName", out var materialName) ? materialName.GetString() ?? string.Empty : string.Empty,
                    PlannedQuantity = ParseDecimal(requestData, "plannedQuantity", 0),
                    ActualQuantity = ParseDecimal(requestData, "actualQuantity", ParseDecimal(requestData, "plannedQuantity", 1)),
                    Unit = requestData.TryGetProperty("unit", out var unit) ? unit.GetString() ?? string.Empty : string.Empty,
                    Batch = requestData.TryGetProperty("batch", out var batch) ? batch.GetString() ?? string.Empty : string.Empty,
                    Remark = requestData.TryGetProperty("remark", out var remark) ? remark.GetString() ?? string.Empty : string.Empty,
                    Specifications = requestData.TryGetProperty("specification", out var spec) ? spec.GetString() ?? string.Empty : string.Empty
                };

                var result = await _packingService.CreatePackingDetailAsync(input);
                return Json(new { code = 0, msg = "添加成功", data = result });
            }
            catch (System.Exception ex)
            {
                // 添加详细的错误日志
                System.Diagnostics.Debug.WriteLine($"CreatePackingDetail Error: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"StackTrace: {ex.StackTrace}");
                return Json(new { code = 1, msg = $"添加失败: {ex.Message}", data = "" });
            }
        }

        /// <summary>
        /// 删除装箱明细
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> DeletePackingDetail(int id)
        {
            try
            {
                await _packingService.DeletePackingDetailAsync(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 获取生产工单选择列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetWorkOrderSelectList(string workOrderCode = "", string productName = "", int page = 1, int limit = 10)
        {
            try
            {
                var input = new GetWorkOrderSelectInputDto
                {
                    WorkOrderCode = workOrderCode,
                    ProductName = productName,
                    SkipCount = (page - 1) * limit,
                    MaxResultCount = limit
                };
                
                var result = await _packingService.GetWorkOrderSelectListAsync(input);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 获取客户选择列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetCustomerSelectList(string customerCode = "", string customerName = "", int page = 1, int pageSize = 10)
        {
            try
            {
                var input = new GetCustomerSelectInputDto
                {
                    CustomerCode = customerCode,
                    CustomerName = customerName,
                    SkipCount = (page - 1) * pageSize,
                    MaxResultCount = pageSize
                };
                
                var result = await _packingService.GetCustomerSelectListAsync(input);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 完成装箱
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> CompletePacking(int id)
        {
            try
            {
                await _packingService.CompletePacking(id);
                return Json(new { code = 0, msg = "完成成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 客户选择页面
        /// </summary>
        [HttpGet]
        public IActionResult SelectCustomer()
        {
            return View();
        }

        /// <summary>
        /// 生产工单选择页面
        /// </summary>
        [HttpGet]
        public IActionResult SelectWorkOrder()
        {
            return View();
        }

        /// <summary>
        /// 装箱明细管理页面
        /// </summary>
        [HttpGet]
        public IActionResult PackingDetails(int packingId)
        {
            ViewBag.PackingId = packingId;
            return View();
        }

        /// <summary>
        /// 子箱选择页面
        /// </summary>
        [HttpGet]
        public IActionResult SelectSubPacking(int parentId)
        {
            ViewBag.ParentId = parentId;
            return View();
        }

        /// <summary>
        /// 获取装箱信息
        /// </summary>
        [HttpGet]
        public async Task<JsonResult> Get(int id)
        {
            try
            {
                var result = await _packingService.GetAsync(id);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 获取装箱明细信息
        /// </summary>
        [HttpGet("GetPackingDetail/{id}")]
        public async Task<JsonResult> GetPackingDetail(int id)
        {
            try
            {
                var result = await _packingService.GetPackingDetailAsync(id);
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 获取子箱列表
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetSubPackingList(int parentId, int page = 1, int limit = 10)
        {
            try
            {
                var input = new GetPackingInputDto
                {
                    ParentId = parentId,
                    SkipCount = (page - 1) * limit,
                    MaxResultCount = limit
                };
                var result = await _packingService.GetListAsync(input);
                return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, data = "" });
            }
        }

        /// <summary>
        /// 移除子箱
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> RemoveSubPacking(int subPackingId)
        {
            try
            {
                await _packingService.RemoveSubPackingAsync(subPackingId);
                return Json(new { code = 0, msg = "移除成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 更新装箱明细
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> UpdatePackingDetail([FromBody] System.Text.Json.JsonElement requestData)
        {
            try
            {
                var input = new UpdatePackingDetailDto
                {
                    Id = ParseInt(requestData, "id", 0),
                    PackingId = ParseInt(requestData, "packingId", 0),
                    WorkOrderCode = requestData.TryGetProperty("workOrderCode", out var workOrderCode) ? workOrderCode.GetString() ?? string.Empty : string.Empty,
                    MaterialCode = requestData.TryGetProperty("materialCode", out var materialCode) ? materialCode.GetString() ?? string.Empty : string.Empty,
                    MaterialName = requestData.TryGetProperty("materialName", out var materialName) ? materialName.GetString() ?? string.Empty : string.Empty,
                    PlannedQuantity = ParseDecimal(requestData, "plannedQuantity", 0),
                    ActualQuantity = ParseDecimal(requestData, "actualQuantity", 0),
                    Unit = requestData.TryGetProperty("unit", out var unit) ? unit.GetString() ?? string.Empty : string.Empty,
                    Batch = requestData.TryGetProperty("batch", out var batch) ? batch.GetString() ?? string.Empty : string.Empty,
                    Specifications = requestData.TryGetProperty("specifications", out var spec) ? spec.GetString() ?? string.Empty : string.Empty,
                    Remark = requestData.TryGetProperty("remark", out var remark) ? remark.GetString() ?? string.Empty : string.Empty
                };
                
                var result = await _packingService.UpdatePackingDetailAsync(input.Id, input);
                return Json(new { code = 0, msg = "更新成功", data = result });
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"UpdatePackingDetail Error: {ex.Message}");
                return Json(new { code = 1, msg = $"更新失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 批量删除装箱明细
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> BatchDeletePackingDetails(int[] ids)
        {
            try
            {
                if (ids != null && ids.Length > 0)
                {
                foreach (var id in ids)
                {
                    await _packingService.DeletePackingDetailAsync(id);
                    }
                }
                return Json(new { code = 0, msg = "批量删除成功" });
            }
            catch (System.Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 测试数据库连接和数据
        /// </summary>
        [HttpGet]
        public async Task<JsonResult> TestData()
        {
            try
            {
                // 直接从服务获取数据进行测试
                var testInput = new GetPackingInputDto();
                var result = await _packingService.GetTreeListAsync(testInput);
                
                return Json(new { 
                    code = 0, 
                    msg = "测试成功", 
                    count = result?.Count ?? 0,
                    data = result,
                    debug = "直接调用服务方法获取数据"
                });
            }
            catch (System.Exception ex)
            {
                return Json(new { 
                    code = 1, 
                    msg = ex.Message, 
                    stackTrace = ex.StackTrace,
                    innerException = ex.InnerException?.Message
                });
            }
        }

        /// <summary>
        /// 安全解析整数
        /// </summary>
        private static int ParseInt(System.Text.Json.JsonElement element, string propertyName, int defaultValue)
        {
            if (!element.TryGetProperty(propertyName, out var prop))
                return defaultValue;
                
            if (prop.ValueKind == System.Text.Json.JsonValueKind.Number)
                return prop.GetInt32();
                
            if (prop.ValueKind == System.Text.Json.JsonValueKind.String)
            {
                var str = prop.GetString();
                if (int.TryParse(str, out var result))
                    return result;
            }
            
            return defaultValue;
        }

        /// <summary>
        /// 安全解析小数
        /// </summary>
        private static decimal ParseDecimal(System.Text.Json.JsonElement element, string propertyName, decimal defaultValue)
        {
            if (!element.TryGetProperty(propertyName, out var prop))
                return defaultValue;
                
            if (prop.ValueKind == System.Text.Json.JsonValueKind.Number)
                return prop.GetDecimal();
                
            if (prop.ValueKind == System.Text.Json.JsonValueKind.String)
            {
                var str = prop.GetString();
                if (decimal.TryParse(str, out var result))
                    return result;
            }
            
            return defaultValue;
        }
    }
} 